package com.platform.common.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;

import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: wangyanginfo
 * Date: 12-9-7
 * Time: 下午2:26
 * To change this template use File | Settings | File Templates.
 */
public class JsonUtil {

    /**
     * 将对象传换成JSON格式字符串
     *
     * @param obj 对象
     * @return JSON格式字符串
     */
    public final static String objectToJSON(Object obj) {
        XStream xstream = new XStream(new JettisonMappedXmlDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        return xstream.toXML(obj);
    }

    /**
     * 将对象传换成JSON格式字符串
     *
     * @param obj         对象
     * @param alias       别名
     * @param cas         需要进行名字转换的Class
     * @param isRootTitle 是否删除根节点
     * @return JSON格式字符串
     */
    public final static String objectToJSON(Object obj, String alias, Class cas, boolean isRootTitle) {
        JsonHierarchicalStreamDriver driver = new JsonHierarchicalStreamDriver();
        XStream xstream = new XStream(driver);
        xstream.alias("rows", cas);
        //xstream.alias(alias, obj.getClass());
        //是否删除根节点
        if (isRootTitle) {
            //删除根节点
            xstream = new XStream(new JsonHierarchicalStreamDriver() {
                public HierarchicalStreamWriter createWriter(Writer out) {
                    return new JsonWriter(out, JsonWriter.DROP_ROOT_MODE);
                }
            });
        }
        return xstream.toXML(obj);
    }

    /**
     * 将对象传换成JSON格式字符串
     *
     * @param obj         对象
     * @param alias       别名
     * @param isRootTitle 是否删除根节点
     * @return JSON格式字符串
     */
    public final static String objectToJSON(Object obj, String alias, boolean isRootTitle) {
        return objectToJSON(obj, alias, obj.getClass(), isRootTitle);
    }

    /**
     * 将对象传换成JSON格式字符串
     *
     * @param obj 对象
     * @return JSON格式字符串
     */
    public final static String objectToJSON(Object obj, boolean isRootTitle) {
        String packageClassName = obj.getClass().getName();
        //获取类名（不带包名）
        String alias = packageClassName.substring(packageClassName.lastIndexOf(".") + 1, packageClassName.length());
        return objectToJSON(obj, alias, isRootTitle);
    }

    public final static Map<String, List> jsonToMap(String jsonStr, Class clazz) throws Exception {
        // 截取字符串前的{符号和字符串后的]}
        jsonStr = jsonStr.substring(1, jsonStr.length() - 2);
        // 替换字符串中的双引号
        jsonStr = jsonStr.replace("\"", "");
        // 替换字符串中的[括号
        jsonStr = jsonStr.replace("[", "");
        // 用]，分割对象集合数组
        String[] strs = jsonStr.split("],");
        // 新建Map对象
        Map<String, List> maps = new HashMap<String, List>();
        for (String str : strs) {
            // 获取集合名称
            String name = str.substring(0, str.indexOf(":"));
            if (str.indexOf(":") + 1 < str.length()) {
                // 获取对象集字符串
                String valuesStr = str.substring(str.indexOf(":") + 1, str.length() - 1);
                // 判断对象集字符串是否为空
                String[] objsStr = valuesStr.split("},");
                List roles = new ArrayList();
                for (String tempStr : objsStr) {
                    // 替换字符串中的{}符号
                    tempStr = tempStr.replace("{", "").replace("}", "");
                    System.out.println(tempStr);
                    // 判断值集合是否为空
                    if (tempStr.trim().length() > 1) {
                        Class cla = Class.forName(clazz.getName());
                        Object obj = cla.newInstance();
                        String[] values = tempStr.split(",");
                        for (String value : values) {
                            value = value.trim();
                            String[] vals = value.split(":");
                            if (vals.length == 2 && vals[1].trim().length() > 0 && !vals[1].trim().equals("null")) {
                                ReflectUtil.setFieldValue(obj, vals[0], vals[1]);
                            }

                        }
                        roles.add(obj);
                    }
                }
                maps.put(name, roles);
            }
        }
        return maps;
    }

}
